import jwt
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

from apps.app01 import models
from apps.app01.extensions import jwtt
from lenovo import settings


class LoginUsernameView(APIView):
    """用户名密码登录"""

    authentication_classes = []

    def post(self, request):
        nickname = request.data.get('nickname')
        password = request.data.get('password')
        user = models.User.objects.filter(nickname=nickname, password=password).first()
        if not user:
            return JsonResponse({'code': 402, 'message': '用户名或密码错误'}, status=402)
        payload = jwtt.jwt_payload_handler(user)
        access_token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
        refresh_token = RefreshToken.for_user(user)
        return JsonResponse(
            {'code': 200, 'message': 'OK', 'data': {'access_token': access_token, 'refresh_token': str(refresh_token)}},
            status=200)